<?php
/**
 * Created by inline.
 * User: swb
 * Date: 2022-10-31
 * Time: 11:00
 */
namespace app\store\controller\api\v1;
use app\common\model\Account;
use library\Controller;
use app\common\controller\BaseApiController;
use app\common\facade\Token;
use app\common\model\SystemUser;
use app\shop\model\ShopOrder;
use app\common\model\ShopMessageTip;
use app\common\model\ShopOrderTip;
use app\shop\model\ShopOrderRefund;
use app\api\service\WechatMiniService;
use think\Db;
use app\shop\model\ShopOrderGoods;
use app\common\model\ShopUserMoneyRecord;
use app\common\model\ShopMember;

class Order extends BaseApiController
{
    //洗衣订单
    public function getIndex(){
        $current = $this->request->param('current');
        $store_id = $this->request->param('store_id');
        if($current == 0){
            $res = ShopOrder::where('store_id',$store_id)->where('type',1)->where('is_pay',1)->where('status',2)->with('user')->select();
        }elseif ($current == 1) {
            $res = ShopOrder::where('store_id',$store_id)->where('type',1)->where('is_pay',1)->where('status',3)->with('user')->select();
        }elseif($current == 2){
            $res = ShopOrder::where('store_id',$store_id)->where('type',1)->where('is_pay',1)->where('status',4)->with('user')->select();
        }elseif($current == 3){
            // $res = ShopOrder::where('store_id',$store_id)->where('type',1)->where('is_pay',1)->where('status',7)->with(['user','recharge'])->select();
            $res = ShopOrderRefund::where(['store_id'=>$store_id,'status'=>1])->with(['user','order'])->select();
        }
        
        $this->successCode($res);
    }
    
    // 洗衣操作
    public function postActivity()
    {
        $order_id = $this->request->post('order_id');
        $status = $this->request->post('status');
        $store_id = $this->request->post('store_id');
        $order = ShopOrder::with('store')->where('status', $status)->get($order_id);
        if ($order) {
            switch ($status){
                case 8:
                    $content = "你的{$order['title']}({$order['store']['name']})订单已接单";
                    $order->status = 2;
                    $order->store_id = $store_id;
                    break;
                case 3:
                    $content = "你的{$order['title']}({$order['store']['name']})订单已洗衣结束,请尽快到店领取衣物";
                    $order->status = 4;
                    break;
                case 4:
                    $content = "你的{$order['title']}({$order['store']['name']})订单已领取衣物";
                    $order->status = 5;
                    break;
                default:
                    $content = "你的{$order['title']}({$order['store']['name']})订单已收件洗衣中,请耐心等待";
                    $order->status = 3;
                    break;
            }
            $order->save();
            if ($order['uid']){
                $data = [
                    'uid' => $order['uid'],
                    'title' => '校园快洗',
                    'content' => $content
                ];
                ShopMessageTip::create($data);
            }
            $this->successCode('成功','');
        } else {
            $this->errCode('该订单无效或已开始洗衣');
        }
    }
    
    /**
     * 同意退款
     * auth:swb
     * 2022/11/8 18:40
     */
    public function postPassRefund()
    {
        $refund_id = $this->request->post('id');
        $refund = ShopOrderRefund::where('status', 1)->get($refund_id, ['order']);
        
        if ($refund) {
            $order = $refund['order'];
            Db::startTrans();
            try {
                if ($order['pay_type'] == 1){
                    $res = WechatMiniService::refund($order['pay_no'],$order['order_no'],$order['total_price'],$refund['price']);
                    if ($res) {
                        $refund->status = 4;
                        $refund->complete_time = date('Y-m-d H:i:s');
                        $refund->save();
                        ShopOrder::where('id', $order['id'])->setField('status', -1);
                        ShopOrderGoods::where('order_id', $order['id'])->setField('status', 2);
                        Account::create([
                            'uid' => $order['uid'],
                            'title' => "{$order['title']}",
                            'desc' => "退款微信钱包 - 订单号：{$order['order_no']}",
                            'money' => $refund['price'],
                            'type' => 2,
                            'store_id' => $order['store_id'],
                            'order_id' => $order['id']
                        ]);
                        $data = [
                            'order_id' => $order['id'],
                            'uid' => $order['uid'],
                            'title' => '退款成功',
                            'content' => "¥{$order['total_price']}已成功退回到支付账户"
                        ];
                    }else {
                        Db::rollback();
                        $this->error('失败1001', '');
                    }
                }elseif ($order['pay_type'] == 3){
                    // halt("3333");
                    $refund->status = 4;
                    $refund->complete_time = date('Y-m-d H:i:s');
                    $refund->save();
                    ShopOrder::where('id', $order['id'])->setField('status', -1);
                    ShopOrderGoods::where('order_id', $order['id'])->setField('status', 2);
                    Account::create([
                        'uid' => $order['uid'],
                        'title' => "{$order['title']}",
                        'desc' => "退款余额钱包 - 订单号：{$order['order_no']}",
                        'money' => $refund['price'],
                        'type' => 2,
                        'store_id' => $order['store_id'],
                        'order_id' => $order['id']
                    ]);
                    ShopUserMoneyRecord::record($order['total_price'],$order['uid'],"预约退款",1,true,"余额支付 - 订单号：{$order['order_no']}");
                    $data = [
                        'order_id' => $order['id'],
                        'uid' => $order['uid'],
                        'title' => '退款成功',
                        'content' => "¥{$order['total_price']}已成功退回到账户余额"
                    ];
                }else{
                    $refund->status = 4;
                    $refund->complete_time = date('Y-m-d H:i:s');
                    $refund->save();
                    $buy_num = ShopOrderGoods::where('order_id',$order['id'])->sum('num');
                    ShopOrderGoods::where('order_id', $order['id'])->setField('status', 2);
                    $rs =ShopMember::where('uid', $order['uid'])->where('status',1)->setDec('use_num', $buy_num);
                    $data = [
                        'order_id' => $order['id'],
                        'uid' => $order['uid'],
                        'title' => '审核成功',
                        'content' => "总{$buy_num}件数已成功退回到账户件数"
                    ];
                }
                ShopOrderTip::create($data);
                Db::commit();
                $this->success('成功');
            } catch (Exception $e) {
                Db::rollback();
                $this->error('失败1002:'.$e->getMessage(), '');
            }
        } else {
            $this->error('售后失败，订单无效', '');
        }
    }
    
    /**
     * 拒绝售后
     * auth:swb
     * 2022/11/8 23:26
     */
    public function postRefused()
    {
        $refund_id = $this->request->post('id');
        $content = $this->request->post('content');
        $order_id = $this->request->post('order_id');
        $res = ShopOrderRefund::where('id', $refund_id)->update(['content' => $content,'status'=>0]);
        // ShopOrder表status字段更新为2，重新进行洗衣
        $order_status = ShopOrder::where('id',$order_id)->update(['status'=>2]);
        $info = ShopOrderRefund::get($refund_id);
        $data = [
            'order_id' => $info['order_id'],
            'uid' => $info['uid'],
            'title' => '审核失败',
            'content' => "审核不通过原因：{$info['content']}"
        ];
        ShopOrderTip::create($data);
    }
    
    /**
     * 输入手机号洗衣
     * auth:swb
     * 2022/11/14 21:41
     */
    public function getPhoneOrder (){
        $phone = $this->request->param('phone');
        $store_id = $this->request->param('store_id');
         
        $userInfo = Db('user')->where('phone',$phone)->find();
         
        //  $orderInfo = ShopOrder::where('uid', $uid)->order('create_at desc')->find();
         $orderInfo = ShopOrder::where('uid', $userInfo['id'])->where('store_id', $store_id)->where('status','in','2,3,4')->order('create_at desc')->with(['user','good'])->select();
         
        //  if($orderInfo['status']==2){
        //         //扫码成功/输入uid 将订单状态已预约2改为洗衣中3
        //         $orderStatus3 = ShopOrder::where('uid', $userInfo['id'])->where('status','2')->where('store_id',$store_id)->update(['status' => '3']);
        //         // 记录第一次扫码的时间
        //         $data_time = ShopOrder::where('uid', $userInfo['id'])->update(['update_time' => strtotime("+70second")]);
        //     }elseif ($orderInfo['status']==3) {
        //         if(time() >= $orderInfo['update_time']){
        //             // 第二次扫码，将订单状态洗衣中3改为已完成
        //             $orderStatus4 = ShopOrder::where('uid', $userInfo['id'])->where('status','3')->where('store_id',$store_id)->update(['status' => '4']);
        //         }else{
        //             $this->errCode(celTime($orderInfo['update_time']));
        //             // $data['errText'] = "重复扫码！请".."后再扫码";
        //         }
        //     }
        $this->successCode($orderInfo);
    }
    
    //订单详情 
    public function getOrderDetails (){
        $order_no = $this->request->param('order_no');
        $orderDetails = ShopOrder::where('order_no',$order_no)->with(['user','good'])->find();
        $this->successCode($orderDetails);
    }
}






















